/*
 * @Description: 默认请求器
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-10-13
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-24
 */

import { HeaderEnum, HttpCodeEnum, MethodEnum, ReloginList, Timeout, TimeOutList } from '@/enum/httpEnum'
import { REQUEST_PLATFORMCODE } from '@/env/config/base'
import env from '@/env/index'
import { wxAuth } from '@/utils/auth'
import { getToken } from '@/utils/storage'
import { reloadCurrPage } from '@/utils/util'

import Rp from '../utils/report-released-1.2.1.min.js'

/** 请求配置 */
const config: IRequestConfig = {
  errTip: true,
}

/** 请求头 */
const header = {
  'content-type': HeaderEnum.CONTENT_TYPE,
  Authorization: '',
}

/**
  请求拦截
*/
const interceptRequest = (data: any, _config?: IRequestConfig) => {
  header['Authorization'] = getToken() ?? ''
  if (_config) {
    config.errTip = _config.errTip ?? true
  }
  data['platformCode'] = REQUEST_PLATFORMCODE
}

/**
  响应拦截-成功
*/
const interceptResponseSuccess = async (res: any, resolve: any, _reject: any, url: string) => {
  const { data } = res
  const { responseCode, responseMessage } = data
  if (responseCode === HttpCodeEnum.SUCCESS) {
    return resolve(data)
  } else if (ReloginList.includes(responseCode)) {
    await wxAuth()
    reloadCurrPage()
    return resolve(data)
  }
  // 接口非响应成功，日志上报
  Rp.reportLog('_VIEW', {
    url: `${env.api}${url}`,
    appVersion: '1.0.3',
    crashInfo: {
      crashName: responseMessage,
      crashType: 'anr',
    },
  })
  console.log('responseMessage: ', responseMessage)
  if (config.errTip) uni.showToast({ title: responseMessage, icon: 'none' })
  return resolve(data)
}

/**
  响应拦截-失败
*/
const interceptResponseError = async (res: any, _resolve: any, reject: any) => {
  const { data } = res
  const { responseCode } = data
  if (ReloginList.includes(responseCode)) {
    await wxAuth()
    reloadCurrPage()
    return reject(data)
  }
  Rp.report('_VIEW', {
    type: 'error',
    msg: responseMessage,
  })
  let errTitle = '系统错误'
  if (TimeOutList.includes(res.errMsg)) errTitle = '连接超时'
  uni.showToast({ title: errTitle, icon: 'none' }) //TODO
  reject(res)
}

/**
  get请求接口
  @param {String} url 请求路径
  @param {String} param 请求参数query
*/
const get = <IRequest, IResponse>(url: string, param: IRequest, _config?: IRequestConfig) => {
  interceptRequest(param, _config)
  return new Promise<IResponse>((resolve, reject) => {
    uni.request({
      url: `${env.api}${url}`,
      header: header,
      data: param as any,
      method: MethodEnum.GET,
      timeout: Timeout,
      success: (res) => interceptResponseSuccess(res, resolve, reject),
      fail: (res) => interceptResponseError(res, resolve, reject),
    })
  })
}

/**
  post请求接口
  @param {String} url 请求路径
  @param {String} data 请求体参数
*/
const post = <IRequest, IResponse>(url: string, data: IRequest, _config?: IRequestConfig) => {
  interceptRequest(data, _config)
  return new Promise<IResponse>((resolve, reject) => {
    uni.request({
      url: `${env.api}${url}`,
      header: header,
      data: data as any,
      method: MethodEnum.POST,
      timeout: Timeout,
      success: (res) => interceptResponseSuccess(res, resolve, reject, url),
      fail: (res) => interceptResponseError(res, resolve, reject),
    })
  })
}

export { get, post }
